package com.bgl.mall.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * @author buguoliang
 * @date 2022/3/22 23:22
 * @since jdk1.8
 */
@EnableOpenApi
@Configuration
@ConditionalOnExpression("${swagger.enable:true}==true")
public class Swagger3Config implements WebMvcConfigurer {

    @Bean
    public Docket createRestApi() {
        List<Response> responses = new ArrayList<>();
        responses.add(new ResponseBuilder().code("401").description("Unauthorized").build());
        responses.add(new ResponseBuilder().code("403").description("Forbidden").build());
        responses.add(new ResponseBuilder().code("404").description("Not Found").build());
        responses.add(new ResponseBuilder().code("500").description("Server Error").build());

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.bgl.mall.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalResponses(HttpMethod.GET, responses)
                .globalResponses(HttpMethod.POST, responses)
                ;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("bglmall商城接口")
                .description("bglmall商城接口")
                .version("1.0")
                .contact(new Contact("buguoliang", "http://www.hikvision.com/", "bgl807856131@163.com"))
                .license("license 地址（可为空）")
                .licenseUrl("http://www.hikvision.com/cn/index.html")
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");

    }
}
